import React, { useEffect, useState, useRef, useCallback } from 'react';
import {
  App,
  Drawer,
  Steps,
  Button,
  Space,
  Divider,
  message,
  Form,
  TreeSelect
} from 'antd';
import { PageContainer } from "@ant-design/pro-layout";
import { useNavigate, useParams } from "umi";
import {
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormDigit,
  ProFormRadio,
  StepsForm,
  ProCard,
  ProFormInstance,
} from '@ant-design/pro-components';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import TreeSelectDropdown from '../components/TreeSelectDropdown';
import { FormattedMessage, useIntl } from '@umijs/max';
import { listPriceRules } from '@/services/rule/price_rule_api';
import { createProduct, updateProduct, getProductInfoConfig } from '@/services/product/product_api';
import { getProviderApiTree } from '@/services/channel/sp_api';
import { PriceRuleVO } from "../constants"
import { set } from 'lodash';


const { Step } = Steps;

interface AddAccountDrawerProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const AddProductDrawer: React.FC = () => {
  const { message } = App.useApp();
  const { id } = useParams<{ id: string }>();
  const intl = useIntl();
  const navigate = useNavigate();
  const formRef = useRef<React.MutableRefObject<ProFormInstance<any> | undefined>[]>([]);
  const form = useRef<ProFormInstance>();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);

  const [basefeeRules, setBasefeeRules] = useState<PriceRuleVO[]>([]);
  const [initBaseFeeRules, setInitBaseFeeRules] = useState<any>([]);

  const [specialChargesRules, setSpecialChargesRules] = useState<PriceRuleVO[]>([]);
  const [initSpecialChargesRules, setInitSpecialChargesRules] = useState<any>([]);
  const [formData, setFormData] = useState<BackendData | null>(null);
  const [editStatus, setEditStatus] = useState(false);
  const [treeData, setTreeData] = useState<[]>([])
  const [treeValue, setTreeValue] = React.useState<string>('');

  useEffect(() => {
    const fetchFeeOptions = async () => {
      setLoading(true);
      try {
        await initServiceProviderTreaData();
        await initBaseFeeRule();
        await initSpecialChargesRule();
        if (id && id !== 'new') {
          await getProductInfo(id);
          setEditStatus(true);
        }
      } finally {
        setLoading(false);
      }

    };
    fetchFeeOptions();
  }, []);


  const calcTypeName = {
    Fixed_Price: intl.formatMessage({ id: "pages.price.calcType.fixedPrice", defaultMessage: "Fixed Price" }),
    Floating_Rate: intl.formatMessage({ id: "pages.price.calcType.floatingRate", defaultMessage: "Floating Rate" }),
    Fixed_Additional: intl.formatMessage({ id: "pages.price.calcType.fixedAdditional", defaultMessage: "Fixed Additional" }),
    Segmented: intl.formatMessage({ id: "pages.price.calcType.Segmented", defaultMessage: "Segmented" }),
  };

  const initServiceProviderTreaData = async () => {
    try {
      // Basic_Rate  Extras_Fee
      // Replace with your actual API endpoint
      const response = await getProviderApiTree();
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      setTreeData(disableNonLeafNodes(response.data));
    } catch (error) {
      console.error('Failed to fetch fee options:', error);

    }
  }

  const disableNonLeafNodes = (data) => {
    return data.map(item => {
      if (item.children && item.children.length > 0) {
        return {
          ...item,
          disabled: true,
          children: disableNonLeafNodes(item.children),
        };
      }
      return item;
    });
  };

  const getProductInfo = async (id: string) => {
    try {
      if (!form.current) return;
      // Basic_Rate  Extras_Fee
      // Replace with your actual API endpoint
      const response = await getProductInfoConfig(id);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      let productInfo = response.data;
      productInfo.prStatus = String(productInfo.prStatus);
      if (productInfo.baseTradingFees) {
        productInfo.baseTradingFees.map((item) => {
          item.calcTypeName = calcTypeName[item.calculationRule]
        })
        // productInfo.baseTradingFee.calcTypeName = calcTypeName[productInfo.baseTradingFee.calculationRule]
      }
      if (productInfo.extraTradingFees) {
        productInfo.extraTradingFees.map((item) => {
          item.calcTypeName = calcTypeName[item.calculationRule]
        })
      }
      console.log("default tree" + productInfo.sp)
      setTreeValue(productInfo.sp);
      formRef?.current?.forEach((formInstanceRef) => {
        formInstanceRef?.current?.setFieldsValue(productInfo);
      });

    } catch (error) {
      console.error('Failed to fetch fee options:', error);

    }
  }

  const initBaseFeeRule = async () => {
    try {
      // Basic_Rate  Extras_Fee
      // Replace with your actual API endpoint
      const response = await listPriceRules("Basic_Rate", {});
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      const options = response.data.map(item => ({
        label: item.ruleName,  // Display text
        value: item.ruleCode   // Actual value stored in form
      }));

      setInitBaseFeeRules(options);
      // console.info("init basefee:"+JSON.stringify(options));
      setBasefeeRules(response.data);
    } catch (error) {
      console.error('Failed to fetch fee options:', error);
      // You might want to set some default options or show an error message
      setBasefeeRules([]);
    }
  }

  const initSpecialChargesRule = async () => {
    try {
      // Basic_Rate  Extras_Fee
      // Replace with your actual API endpoint
      const response = await listPriceRules("Extras_Fee", {});
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      const options = response.data.map(item => ({
        label: item.ruleName,  // Display text
        value: item.ruleCode   // Actual value stored in form
      }));
      setInitSpecialChargesRules(options);
      // console.info("init basefee:"+JSON.stringify(options));
      setSpecialChargesRules(response.data);
    } catch (error) {
      console.error('Failed to fetch fee options:', error);
      // You might want to set some default options or show an error message
      setBasefeeRules([]);
    }
  }

  // const [form] = useForm(); // 创建一个表单实例
  const basefeeRulesChange = (index: any, selectedFeeValue: any) => {
    // console.log("base rule:" + JSON.stringify(selectedFeeValue));
    if (!form.current) return;
    // 1. 找到选中的收费规则对象    
    const selectedFee = basefeeRules.find(
      (rule) => rule.ruleCode === selectedFeeValue
    );
    // console.log("base rule:" + JSON.stringify(selectedFee));
    if (selectedFee) {
      selectedFee.calcuationRuleName = calcTypeName[selectedFee?.calculationRule];
    }
    console.log("base rule:" + JSON.stringify(selectedFee));
    form.current.setFieldsValue({
      baseTradingFees: {
        [index]: {
          id: selectedFee?.id || "",
          ruleCode: selectedFee?.ruleCode || "",
          calcTypeName: selectedFee?.calcuationRuleName || "",
          ruleValue: selectedFee?.ruleValue || "",
          description: selectedFee?.description || "",
        }
      }
    });
  };

  const specialChargeRulesChange = (index: any, selectedSpecialFeeValue: any) => {
    // 1. 找到选中的收费规则对象
    if (!form.current) return;
    // console.log(
    //   "special rule:" + index + "," + JSON.stringify(selectedSpecialFeeValue)
    // );
    const selectedFee = specialChargesRules.find(
      (rule) => rule.ruleCode === selectedSpecialFeeValue
    );

    if (selectedFee) {
      selectedFee.calcuationRuleName = calcTypeName[selectedFee?.calculationRule]
    }
    //  console.log("special rule info:" + JSON.stringify(selectedFee));
    form.current.setFieldsValue({
      extraTradingFees: {
        [index]: {
          id: selectedFee?.id || "",
          ruleCode: selectedFee?.ruleCode || "",
          calcTypeName: selectedFee?.calcuationRuleName || "",
          ruleValue: selectedFee?.ruleValue || "",
          description: selectedFee?.description || "",
        },
      },
    });
    //  console.log(form.current.getFieldsValue());
  };

  const onTreeChange = (newValue) => {
    console.log("treeSelect:" + newValue);
    setTreeValue(newValue);
  }


  const resetForm = () => {
    if (!form.current) return;
    // form.current.resetFields();
    setCurrentStep(0);
  };
  const handleCancel = () => {
    resetForm();
    navigate(-1);
  };



  const handleSubmit = async (value) => {
    try {
      setLoading(true);
      let response;
      if (value.prId) {
        response = await updateProduct(value);
      } else {
        response = await createProduct(value);
      }

      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
        return false;
      }
      resetForm();
      handleCancel();
      message.success(intl.formatMessage({ id: 'pages.product.submit.success' }));
    } catch (error) {
      message.error(intl.formatMessage({ id: 'pages.product.submit.error' }));
    } finally {
      setLoading(false);
    }
  };
// const isLastStep = currentStep === steps.length - 1;
  const pageChange = (number) => {
    console.log("page:" + number)
  }
  
  return (
    <PageContainer extra={[<Button onClick={handleCancel}>{intl.formatMessage({ id: 'pages.cancel' })}</Button>]}>
      <StepsForm
        formMapRef={formRef}
        formRef={form}
        onCurrentChange={pageChange}
        onFinish={async (values) => {
          handleSubmit(values);
        }}
        formProps={{
          validateMessages: {
            required: intl.formatMessage({ id: 'pages.form.required' }),
          },
        }}
      >
        <StepsForm.StepForm
          name="base"
          title={intl.formatMessage({ id: 'pages.product.step.basic' })}
          onFinish={async () => {
            return true;
          }}
        >
          <ProCard
            title={intl.formatMessage({ id: 'pages.product.basicInfo' })}
            bordered
            headerBordered
            collapsible
            loading={loading}
            style={{
              marginBlockEnd: 16,
              minWidth: 800,
              maxWidth: "100%",
            }}
          >
            <div style={{ marginTop: 40 }}>
              <ProFormText name="prId" hidden />
              <ProFormText
                name="prName"
                label={intl.formatMessage({ id: 'pages.product.name' })}
                placeholder={intl.formatMessage({ id: 'pages.product.name.placeholder' })}
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.product.name.required' }) }]}
              />
              <ProFormText
                name="prCode"
                label={intl.formatMessage({ id: 'pages.product.code' })}
                disabled={editStatus}
                placeholder={intl.formatMessage({ id: 'pages.product.code.placeholder' })}
                rules={[
                  { required: true, message: intl.formatMessage({ id: 'pages.product.code.required' }) },
                  {
                    pattern: /^[A-Za-z0-9_]+$/,
                    message: intl.formatMessage({ id: 'pages.product.code.invalid' })
                  }
                ]}
              />
              <Form.Item
                name="sp"
                label={intl.formatMessage({ id: 'pages.product.supplier' })}
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.product.supplier.required' }) }]}
              >
                <TreeSelect
                  showSearch
                  style={{ width: '100%' }}
                  value={treeValue}
                  styles={{
                    popup: { root: { maxHeight: 400, overflow: 'auto' } },
                  }}
                  placeholder={intl.formatMessage({ id: 'pages.product.supplier.placeholder' })}
                  allowClear
                  onChange={onTreeChange}
                  treeData={treeData}
                />
              </Form.Item>
              <ProFormRadio.Group
                name="prStatus"
                label={intl.formatMessage({ id: 'pages.product.status' })}
                style={{ width: "50%" }}
                rules={[{ required: true }]}
                initialValue='1'
                options={[
                  {
                    label: intl.formatMessage({ id: "pages.status.enabled" }),
                    value: "0",
                  },
                  {
                    label: intl.formatMessage({ id: "pages.status.disabled" }),
                    value: "1",
                  },
                ]}
              />
              <ProFormTextArea
                name="remask"
                label={intl.formatMessage({ id: 'pages.product.remark' })}
                placeholder=""
                fieldProps={{ rows: 4 }}
              />
            </div>
          </ProCard>
        </StepsForm.StepForm>
        <StepsForm.StepForm 
          name="rule" 
          title={intl.formatMessage({ id: 'pages.product.step.feeRule' })} 
          loading={loading}
        >
          <ProCard
            style={{
              minWidth: 800,
              marginBlockEnd: 16,
              maxWidth: "100%",
            }}
          >
            <div style={{ marginTop: 40 }}>
              <h3>{intl.formatMessage({ id: 'pages.product.baseFeeRule' })}</h3>
              <Divider></Divider>
              <Form.List name="baseTradingFees">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Space
                        key={key}
                        align="baseline"
                        style={{ display: "flex", marginBottom: 8, width: "100%" }}
                      >
                        <ProFormSelect
                          name={[name, 'ruleName']}
                          label={intl.formatMessage({ id: 'pages.product.feeRuleName' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.feeRuleName.placeholder' })}
                          rules={[{ required: true, message: intl.formatMessage({ id: 'pages.product.feeRuleName.required' }) }]}
                          fieldProps={{ style: { width: 180 }, onChange: (value) => { basefeeRulesChange(name,value); }}}
                          options={initBaseFeeRules}
                        />
                        <ProFormText name={[name, 'id']} hidden />
                        <div style={{ flex: 1 }} />
                        <ProFormText
                          name={[name, 'ruleCode']}
                          label={intl.formatMessage({ id: 'pages.product.ruleCode' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.ruleCode' })}
                          fieldProps={{ style: { width: 180 }, readOnly: true }}
                        />
                        <div style={{ flex: 1 }} />
                        <ProFormText
                          name={[name, 'calcTypeName']}
                          label={intl.formatMessage({ id: 'pages.product.calcType' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.calcType' })}
                          fieldProps={{ style: { width: 180 }, readOnly: true }}
                        />
                        <div style={{ flex: 1 }} />
                        <ProFormText
                          name={[name, 'ruleValue']}
                          label={intl.formatMessage({ id: 'pages.product.ruleValue' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.ruleValue' })}
                          fieldProps={{ style: { width: 180 }, readOnly: true }}
                        />
                        <div style={{ flex: 1 }} />
                        <ProFormText
                          {...restField}
                          name={[name, 'description']}
                          label={intl.formatMessage({ id: 'pages.product.description' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.description' })}
                          fieldProps={{ readOnly: true }}
                        />
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      </Space>
                    ))}
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      icon={<PlusOutlined />}
                      style={{ width: '100%', marginBottom: 16 }}
                    >
                      {intl.formatMessage({ id: 'pages.product.addFeeRule' })}
                    </Button>
                  </>
                )}
              </Form.List>
            </div>
            <div style={{ marginTop: 40 }}>
              <h3>{intl.formatMessage({ id: 'pages.product.extraFeeRule' })}</h3>
              <Divider></Divider>
              <Form.List name="extraTradingFees">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name: fieldName, ...restField }) => (
                      <Space key={key} style={{ display: "flex", marginBottom: 8 }} align="baseline">
                        <ProFormSelect
                          name={[fieldName, "ruleName"]}
                          label={intl.formatMessage({ id: 'pages.product.extraFeeName' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.extraFeeName.placeholder' })}
                          rules={[{ required: true, message: intl.formatMessage({ id: 'pages.product.extraFeeName.required' }) }]}
                          fieldProps={{ style: { width: 180 }, onChange: (value) => { specialChargeRulesChange(fieldName, value); }}}
                          options={initSpecialChargesRules}
                        />
                        <ProFormText name={[fieldName, "id"]} hidden />
                        <ProFormText
                          name={[fieldName, "ruleCode"]}
                          label={intl.formatMessage({ id: 'pages.product.ruleCode' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.ruleCode' })}
                          fieldProps={{ style: { width: 180 }, readOnly: true }}
                        />
                        <div style={{ flex: 1 }} />
                        <ProFormText
                          name={[fieldName, "calcTypeName"]}
                          label={intl.formatMessage({ id: 'pages.product.calcType' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.calcType' })}
                          fieldProps={{ style: { width: 180 }, readOnly: true }}
                        />
                        <div style={{ flex: 1 }} />
                        <ProFormText
                          name={[fieldName, "ruleValue"]}
                          label={intl.formatMessage({ id: 'pages.product.ruleValue' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.ruleValue' })}
                          fieldProps={{ style: { width: 180 }, readOnly: true }}
                        />
                        <div style={{ flex: 1 }} />
                        <ProFormText
                          name={[fieldName, "description"]}
                          label={intl.formatMessage({ id: 'pages.product.description' })}
                          placeholder={intl.formatMessage({ id: 'pages.product.description' })}
                          fieldProps={{ readOnly: true }}
                        />
                        <MinusCircleOutlined onClick={() => remove(fieldName)} />
                      </Space>
                    ))}
                    <Form.Item>
                      <Button
                        type="dashed"
                        onClick={() => add()}
                        block
                        icon={<PlusOutlined />}
                      >
                        {intl.formatMessage({ id: 'pages.product.addExtraFeeRule' })}
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </div>
          </ProCard>
        </StepsForm.StepForm>
        <StepsForm.StepForm name="time" title={intl.formatMessage({ id: 'pages.product.step.other' })}>
          <ProCard
            style={{
              marginBlockEnd: 16,
              minWidth: 800,
              maxWidth: "100%",
            }}
          >
            <ProFormText
              name="other-config"
              label={intl.formatMessage({ id: 'pages.product.otherConfig' })}
              placeholder={intl.formatMessage({ id: 'pages.product.otherConfig.placeholder' })}
              fieldProps={{ readOnly: true }}
            />
          </ProCard>
        </StepsForm.StepForm>
      </StepsForm>
    </PageContainer>
  );
};

export default AddProductDrawer;